import { setStore, getStore, removeStore } from "src/service/common";
import {RDIRECTURL} from "src/config/weiXinrRdirectUrl";


//判断是否为微信浏览器
export const isWeiXin = () => {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  }
  return false;
};
//微信登陆
export const weiXinLogin = () => {
  if (isWeiXin()) {
  }
};

/**
 * 微信授权
 */
export const wxLoginOAuth = () => {
    removeStore('token');
    if (isWeiXin()) {
    const appid = "xxx"; // 微信appid
    const redirect_uri = RDIRECTURL; //重定向地址，已实现打包的时候自动切换
    const url =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      appid +
      "&redirect_uri=" +
      encodeURIComponent(redirect_uri) +
      "&response_type=code&scope=snsapi_userinfo&state=WXClient#wechat_redirect";
    window.location.href = url;
  }
};

//微信支付
export const weiXinPay = (data, callback) => {
  var wxConfigObj = {
    appId: data.appId,
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.package,
    signType: data.signType,
    paySign: data.sign
  };

  function onBridgeReady() {
    window.WeixinJSBridge.invoke("getBrandWCPayRequest", wxConfigObj, function(
      res
    ) {
      if (res.err_msg == "get_brand_wcpay_request:ok") {
        callback && callback(res);
      } // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
      if (res.err_msg == "get_brand_wcpay_request:cancel") {
        // common.loadWarn('支付遇到问题，您取消了支付');
      }
      if (res.err_msg == "get_brand_wcpay_request:fail") {
        // common.myConfirm('支付遇到问题,您可能需要重新登录', '', function () {
        //   obj.wxLoginOAuth();
        // });
      }
    });
  }
  if (typeof window.WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
      document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
};

//判断是否微信登录过
export const isLogin = ()=>{
  let token = getStore("token");
  if(token){
    return true;
  }else{
    return false;
  }
}